package com.technician.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.technician.mapper.MenuMapper;
import com.technician.mapper.UserMapper;
import com.technician.model.entity.User;
import com.technician.model.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询该用户并且返回
        // 首先我们要定义一个 返回类型 UserDetails 去接收 User
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果 用户为 null 则 抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误...");
        }

        //封装权限
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        // 把 user 封装成 LoginUser 返回
        return new LoginUser(user,list);
    }
}